package cn.shujuhai.qtadmin.platform.pluging.security;

import java.util.ArrayList;
import java.util.stream.Collectors;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.shujuhai.qtadmin.platform.domain.SysMenu;
import cn.shujuhai.qtadmin.platform.domain.SysUser;
import cn.shujuhai.qtadmin.platform.mapper.SysMenuMapper;
import cn.shujuhai.qtadmin.platform.mapper.SysUserMapper;
import cn.shujuhai.qtadmin.platform.pluging.logging.BusinessType;
import cn.shujuhai.qtadmin.platform.pluging.logging.Logging;

/**
 * 用户
 *
 * @author dch798
 * @date 2021/08/22 23:44
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    final SysUserMapper sysUserMapper;
    final SysMenuMapper sysMenuMapper;

    public UserDetailsServiceImpl(SysUserMapper sysUserMapper, SysMenuMapper sysMenuMapper) {
        this.sysUserMapper = sysUserMapper;
        this.sysMenuMapper = sysMenuMapper;
    }

    @Override
    @Logging(title = "登陆", describe = "登陆", type = BusinessType.QUERY)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        SysUser userInfo = new SysUser().selectOne(new QueryWrapper<SysUser>().eq("email", username));
        // 判断用户是否存在
        if (ObjectUtil.isEmpty(userInfo)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        var permissions = this.sysUserMapper.getUserPermissions(userInfo.getId());
        var openPermissions = this.sysMenuMapper.selectList(new QueryWrapper<SysMenu>().eq("perms", "open"));
        openPermissions.forEach(op -> permissions.add(op.getHref()));
        var finallyPermissions = permissions.stream().distinct().collect(Collectors.toList());
        var authorities = new ArrayList<GrantedAuthority>();
        finallyPermissions.forEach(p -> {
            if (CharSequenceUtil.isNotBlank(p)) {
                authorities.add(new SimpleGrantedAuthority(p));
            }
        });
        userInfo.setAuthorities(authorities);
        return userInfo;
    }
}
